<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UserDept;

class DeptController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = (new UserDept)->buildTree();
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return response()->json($responseJson);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate(
            [
                'id' => 'nullable|integer',
                'parentId' => 'nullable|integer',
                'label' => 'required',
                'sort' => 'integer',
                'status' => '',
                'remark' => '',
            ]
        );
        $validatedData['id'] = $validatedData['id'] ?? 0;
        $validatedData['parentId'] = $validatedData['parentId'] ?? 0;
        $validatedData['status'] = $validatedData['status'] ?? 0;
        $validatedData['remark'] = $validatedData['remark'] ?? '';
        if (empty($validatedData['id'])) { //新增
            $data = UserDept::create($validatedData);
        } else { //更新
            $data = UserDept::findOrFail($validatedData['id']);
            $data->update($validatedData);
        }
        return response()->json([
            'code' => 200,
            'message' => '成功',
            'data' => ''
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $menu = UserDept::findOrFail($num);
                $menu->delete();
            }
        } else {
            $menu = UserDept::findOrFail($ids);
            $menu->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }


}
